package com.xyd.servlet;

import com.xyd.entity.Order;
import com.xyd.service.impl.OrderServiceImpl;
import com.xyd.util.GetPageUtil;
import com.xyd.util.JsonUtil;
import com.xyd.util.TotalPageUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/OrderGetAllByPageServlet")
public class OrderGetAllByPageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        OrderServiceImpl orderService = new OrderServiceImpl();
        HttpSession session=request.getSession();
        GetPageUtil getPageUtil = new GetPageUtil();
        TotalPageUtil totalPageUtil = new TotalPageUtil();
        String x=request.getParameter("id");
        if (x==null){
            x="1";
        }
        if (x.equals("上一页")){
            Object z= session.getAttribute("myid");
            int p=(int)z-1;
            x=Integer.toString(p);
        }
        if (x.equals("下一页")){
            Object z= session.getAttribute("myid");
            int p=(int)z+1;
            x=Integer.toString(p);
        }
        int page=Integer.parseInt(x);
        int totalPage=orderService.getCountOrder();
        int maxPage = TotalPageUtil.getTotalPage(totalPage,GetPageUtil.PAGESiZE);
        if (page>maxPage){
            page=maxPage;
        }if (page<1){
            page=1;
        }
        int start=getPageUtil.getStart(page);
        List<Order> list=orderService.getAllOrderByPage(start,GetPageUtil.PAGESiZE);
        session.setAttribute("myid",page);
        JsonUtil.toJson(response,list);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
